package com.scisoft.scan.control.quickcheck;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nlscan.android.scan.ScanManager;
import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.PartBean;
import com.scisoft.scan.data.quickcheck.InitCheckScanBean;
import com.scisoft.scan.data.quickcheck.InitCheckStatisticsBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_QuickCheck;

public class InitCheckActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private ImageView iv_query; //搜索按钮
    private ClearEditText et_bar;
    private InitCheckAdapter initCheckAdapter;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    float lastY = 0;
    private PartBean partBean;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_init_check);

        //扫码框
        et_bar = findViewById(R.id.et_bar);
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //搜索框
        iv_query = findViewById(R.id.iv_query);
        iv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScanData(et_bar.getUpperText().toString());
            }
        });
        //列表
        mRecyclerView = findViewById(R.id.lv_data);
        initCheckAdapter = new InitCheckAdapter(InitCheckActivity.this);
        initCheckAdapter.setMultiPage(false);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;
        initCheckAdapter.setItemLayout(R.layout.item_initcheckscaninfo, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //滚动的时候清空左滑按钮
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(event.getY() - lastY) > 5)
                            initCheckAdapter.clearLeftMenuList();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(initCheckAdapter);

        BindData(InitCheckActivity.this,null);

    }

    //查询服务
    class QueryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private InitCheckStatisticsBean initCheckStatisticsBean;
        private String mbarCode;

        QueryTask(Context context, String barCode) {
            super();
            mcontext = context;
            mbarCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //查询配件
                BarCodeBean barCodeBean = WebServiceHelper.ParseBarCode(mbarCode);
                if (barCodeBean.barType != BarCodeBean.BAR_PART) {
                    msg = "配件二维码无效";
                    return msg;
                }
                if (barCodeBean.partBean == null) {
                    msg = "未查询到有效配件";
                    return msg;
                }
                partBean = barCodeBean.partBean;
                //上传配件
                msg = WebServiceHelper_QuickCheck.QUICKCHECK_05(partBean.partNo, partBean.supplierCode, mbarCode);
                if (msg.contains("成功")) {
                    //查询统计信息
                    initCheckStatisticsBean = WebServiceHelper_QuickCheck.QUICKCHECK_06(partBean.partNo, partBean.supplierCode);
                    msg = "成功";
                }
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, initCheckStatisticsBean);
            } else {
                BindData(mcontext, null);
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //删除唯一码服务
    class ScanDeleteTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String partNo;
        private String serialNo;
        private String supplierCode;
        private InitCheckStatisticsBean initCheckStatisticsBean;

        ScanDeleteTask(Context context, String partNo,  String supplierCode,String serialNo) {
            super();
            mcontext = context;
            this.partNo = partNo;
            this.serialNo = serialNo;
            this.supplierCode = supplierCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_QuickCheck.QUICKCHECK_07(partNo, supplierCode,serialNo);
                if (msg.contains("成功")) {
                    //查询统计信息
                    initCheckStatisticsBean = WebServiceHelper_QuickCheck.QUICKCHECK_06(partBean.partNo, partBean.supplierCode);
                    msg = "成功";
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, initCheckStatisticsBean);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //绑定数据
    private void BindData(Context context,InitCheckStatisticsBean data) {
        //信息框
        LinearLayout ll_info = findViewById(R.id.ll_info);
        View v_1  = findViewById(R.id.v_1);
        View v_2  = findViewById(R.id.v_2);
        TextView tv_partNo = findViewById(R.id.tv_partNo);
        TextView tv_partName = findViewById(R.id.tv_partName);
        TextView tv_supplierCode = findViewById(R.id.tv_supplierCode);
        TextView tv_supplierName = findViewById(R.id.tv_supplierName);
        TextView tv_count = findViewById(R.id.tv_count);
        if (data != null) {
            ll_info.setVisibility(View.VISIBLE);
            v_1.setVisibility(View.VISIBLE);
            v_2.setVisibility(View.VISIBLE);
            tv_partNo.setText(data.partNo);
            tv_partName.setText(data.partName);
            tv_supplierCode.setText(data.supplierCode);
            tv_supplierName.setText(data.supplierName);
            tv_count.setText(String.valueOf(data.serialNoList.size()));

            if (data.serialNoList.size() > 0) {
                mRecyclerView.setVisibility(View.VISIBLE);
                //数据
                initCheckAdapter.clearLeftMenuList();
                initCheckAdapter.clearAddItem(data.serialNoList);
            } else {
                mRecyclerView.setVisibility(View.INVISIBLE);
            }
        }
        else{
            ll_info.setVisibility(View.INVISIBLE);
            mRecyclerView.setVisibility(View.INVISIBLE);
            v_1.setVisibility(View.INVISIBLE);
            v_2.setVisibility(View.INVISIBLE);
        }
    }

    //适配器相关功能
    class InitCheckAdapter extends CommonAdapter<InitCheckScanBean> {
        //构造函数
        public InitCheckAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final InitCheckScanBean initCheckScanBean, int position) {
            //获取相应索引的ItemBean对象
            final InitCheckScanBean bean = mList.get(position);
            //唯一码
            TextView tv_partNo = holder.getView(R.id.tv_partNo);

            //设置控件的对应属性值
            tv_partNo.setText(bean.serialNo);

            //删除按钮
            TextView tv_delete = holder.getView(R.id.tv_delete);
            tv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //删除
                    CommonUtil.showPress(InitCheckActivity.this);
                    ScanDeleteTask scanDeleteTask = new ScanDeleteTask(InitCheckActivity.this, partBean.partNo, initCheckScanBean.supplierCode, initCheckScanBean.serialNo);
                    scanDeleteTask.execute();

                }
            });

        }
    }

    //region 以下为扫码相关

    private void ScanData(String barCode) {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryTask queryBarCodeTask = new QueryTask(InitCheckActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        registerReceiver(mResultReceiver, intFilter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ScanManager.ACTION_SEND_SCAN_RESULT.equals(action)) {
                byte[] bvalue1 = intent.getByteArrayExtra(ScanManager.EXTRA_SCAN_RESULT_ONE_BYTES);
                String svalue1 = null;
                try {
                    if (bvalue1 != null) {
                        svalue1 = new String(bvalue1, "GBK");
                        ScanData(svalue1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(InitCheckActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };
    //endregion

}
